#include "StdAfx.h"
#include "YUVFrameConverter.hxx"


YUVFrameConverter::YUVFrameConverter(void)
{
	_py = 0;
	_pu = 0;
	_pv = 0;
	_pu_big = 0;
	_pv_big = 0;
	_image = 0;

	_frameWidth = 0;
	_frameHeight = 0;
}


YUVFrameConverter::~YUVFrameConverter(void)
{
	if( _py )
	{
		cvReleaseImage( &_py );
		_py = 0;
	}

	if( _pu )
	{
		cvReleaseImage( &_pu );
		_pu = 0;
	}

	if( _pv )
	{
		cvReleaseImage( &_pv );
		_pv = 0;
	}

	if( _pu_big )
	{
		cvReleaseImage( &_pu_big );
		_pu_big = 0;
	}

	if( _pv_big )
	{
		cvReleaseImage( &_pv_big );
		_pv_big = 0;
	}

	if( _image )
	{
		cvReleaseImage( &_image );
		_image = 0;
	}
}

void YUVFrameConverter::initialize()
{
	_py = cvCreateImage(cvSize( _frameWidth ,_frameHeight ), IPL_DEPTH_8U, 1);
	_pu = cvCreateImage(cvSize( _frameWidth/2, _frameHeight/2 ), IPL_DEPTH_8U, 1);
	_pv = cvCreateImage(cvSize( _frameWidth/2, _frameHeight/2 ), IPL_DEPTH_8U, 1);

    _pu_big = cvCreateImage(cvSize( _frameWidth ,_frameHeight ), IPL_DEPTH_8U, 1);
    _pv_big = cvCreateImage(cvSize( _frameWidth ,_frameHeight ), IPL_DEPTH_8U, 1);

	_image = cvCreateImage(cvSize( _frameWidth, _frameHeight ), IPL_DEPTH_8U, 3);
}

void YUVFrameConverter::convert( char* buffer, char* fileName )
{
	int offset = 0;
	int tsize = _frameWidth * _frameHeight;
	
	memcpy( _py->imageData , buffer + offset, tsize );
	
	offset += tsize;
	memcpy( _pu->imageData , buffer + offset, tsize / 4 );
	
	offset += tsize / 4;
	memcpy( _pv->imageData , buffer + offset, tsize / 4 );
	
	cvResize( _pu, _pu_big, CV_INTER_LINEAR);
	cvResize( _pv, _pv_big, CV_INTER_LINEAR);
	
	cvMerge( _py, _pu_big, _pv_big, NULL, _image);
	
	cvCvtColor( _image,_image,CV_YCrCb2BGR);
}

void YUVFrameConverter::copyImageData( char* dst )
{
	if( dst )
		memcpy( dst, _image->imageData, _image->imageSize );
}
